package com.lagou;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lagou.request.RpcRequest;
import com.lagou.serialize.JSONSerializer;
import com.lagou.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(){
        this.clazz = RpcRequest.class;
        this.serializer = new JSONSerializer();
    }
//    public RpcDecoder(Class<?> clazz){
//        new RpcDecoder(clazz,null);
//    }
    public RpcDecoder(Class<?> clazz , Serializer serializer){
        this.clazz = clazz;
        if(serializer == null)
            this.serializer = new JSONSerializer();
        else
            this.serializer = serializer;
    }


    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int readInt = byteBuf.readInt();
        //int t = byteBuf.readableBytes();
        byte[] bytes = new byte[readInt];
        byteBuf.readBytes(bytes);
        RpcRequest request = (RpcRequest) serializer.deserialize(clazz,bytes);
        Object result = request.getResult();
        //此处和json存在耦合，应该分离出去
        if(result instanceof JSONArray){
            List resultList = ((JSONArray)result).toJavaList(request.getResultType());
            request.setResult(resultList);
        }else if(result instanceof JSONObject){
            request.setResult(((JSONObject)result).toJavaObject(request.getResultType()));
        }
        list.add(request);
        System.out.println(request);
    }
}
